#!/bin/bash

# 配置参数
INSTALL_DIR="/home/remote/project/profile"
SCRIPT_NAME="gpio-control"
CONFIG_FILE="${INSTALL_DIR}/gpio_config.ini"  # 配置文件路径
GPIO_DIR=/sys/class/gpio

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 确保安装目录存在
mkdir -p "$INSTALL_DIR" || {
    echo "错误：无法创建安装目录 $INSTALL_DIR"
    exit 1
}

# 从配置文件加载 GPIO（若不存在则初始化）
load_gpio_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        echo "# GPIO 配置文件" > "$CONFIG_FILE"
        echo "GPIO4_B3=139,gpio-value=1" >> "$CONFIG_FILE"
        echo "GPIO4_B4=140,gpio-value=1" >> "$CONFIG_FILE"
        echo "# 添加新 GPIO 格式：名称=编号,gpio-value=0/1" >> "$CONFIG_FILE"
        echo -e "${YELLOW}已创建初始配置文件：$CONFIG_FILE${NC}"
    fi
    
    # 读取配置到关联数组
    declare -gA GPIO_MAP=()
    declare -gA GPIO_VALUE=()
    while IFS= read -r line || [ -n "$line" ]; do
        [[ "$line" =~ ^#|^[[:space:]]*$ ]] && continue  # 跳过注释和空行
        
        # 提取名称和参数部分
        name_part="${line%%=*}"
        param_part="${line#*=}"
        
        # 提取编号
        gpio_num="${param_part%%,*}"
        GPIO_MAP["$name_part"]="$gpio_num"
        
        # 提取gpio-value（如果存在）
        value_str="${param_part#*,}"
        if [[ "$value_str" == *"gpio-value"* ]]; then
            gpio_value="${value_str#*=}"
            GPIO_VALUE["$name_part"]="${gpio_value%%[[:space:]]*}"
        else
            GPIO_VALUE["$name_part"]="1"  # 默认高电平
        fi
    done < "$CONFIG_FILE"
    
    if [ ${#GPIO_MAP[@]} -eq 0 ]; then
        echo -e "${RED}错误：配置文件中无有效 GPIO 定义！${NC}"
        exit 1
    fi
}

# 日志函数
log() {
    local level="$1"
    local msg="$2"
    local color=$(case "$level" in INFO) echo "$GREEN" ;; WARN) echo "$YELLOW" ;; ERROR) echo "$RED" ;; *) echo "$NC" ;; esac)
    echo -e "$color$(date '+%Y-%m-%d %H:%M:%S') - $level: $msg$NC"
}

# 导出 GPIO（带权限处理）
export_gpio() {
    local gpio_num="$1"
    local gpio_path="$GPIO_DIR/gpio$gpio_num"
    [ -d "$gpio_path" ] && return 0
    
    log INFO "导出 GPIO$gpio_num..."
    echo "$gpio_num" | sudo tee "$GPIO_DIR/export" >/dev/null || {
        log ERROR "导出 GPIO$gpio_num 失败！权限不足或编号错误"
        exit 1
    }
    sleep 0.1
}

# 设置 GPIO 电平
set_gpio() {
    local gpio_name="$1"
    local gpio_num="${GPIO_MAP[$gpio_name]}"
    local gpio_value="${GPIO_VALUE[$gpio_name]}"
    
    [ -z "$gpio_num" ] && { log ERROR "未知 GPIO: $gpio_name"; exit 1; }
    
    export_gpio "$gpio_num"
    log INFO "设置 $gpio_name ($gpio_num) 为输出模式..."
    echo "out" | sudo tee "$GPIO_DIR/gpio$gpio_num/direction" >/dev/null
    
    local level_text="高电平"
    if [ "$gpio_value" = "0" ]; then
        level_text="低电平"
    fi
    
    log INFO "设置 $gpio_name ($gpio_num) 为$level_text..."
    echo "$gpio_value" | sudo tee "$GPIO_DIR/gpio$gpio_num/value" >/dev/null
}

# 读取 GPIO 状态
read_status() {
    local gpio_name="$1"
    local gpio_num="${GPIO_MAP[$gpio_name]}"
    [ -z "$gpio_num" ] && { log ERROR "未知 GPIO: $gpio_name"; return 2; }
    
    local gpio_path="$GPIO_DIR/gpio$gpio_num"
    [ ! -f "$gpio_path/value" ] && { log ERROR "GPIO$gpio_num 未导出"; return 2; }
    
    local status=$(cat "$gpio_path/value")
    echo "$status"
    return 0
}

# 显示所有 GPIO 状态
show_all_status() {
    echo -e "${YELLOW}==== GPIO 状态汇总 ====${NC}"
    for name in "${!GPIO_MAP[@]}"; do
        local num="${GPIO_MAP[$name]}"
        read_status "$name" >/dev/null
        local status=$?
        local level=$(cat "$GPIO_DIR/gpio$num/value" 2>/dev/null || echo "-1")
        
        echo -n "$name ($num): "
        if [ "$level" -eq 1 ]; then
            echo -e "${GREEN}高电平${NC}"
        elif [ "$level" -eq 0 ]; then
            echo -e "${RED}低电平${NC}"
        else
            echo -e "${YELLOW}未导出/未知${NC}"
        fi
    done
}

# 主逻辑
load_gpio_config

case "$1" in
    enable)
        # 启用单个或所有 GPIO
        if [ -z "$2" ]; then
            log ERROR "请指定要启用的 GPIO 名称（如 $SCRIPT_NAME enable GPIO4_B3）"
            exit 1
        elif [ "$2" == "all" ]; then
            for name in "${!GPIO_MAP[@]}"; do
                set_gpio "$name"
            done
        else
            set_gpio "$2"
        fi
        ;;
    
    status)
        # 查看单个或所有 GPIO 状态
        if [ -z "$2" ]; then
            show_all_status
        elif [ "$2" == "all" ]; then
            show_all_status
        else
            read_status "$2" >/dev/null
            local exit_code=$?
            [ $exit_code -eq 0 ] && {
                local level=$(cat "$GPIO_DIR/gpio${GPIO_MAP[$2]}/value")
                [ "$level" -eq 1 ] && log INFO "$2 状态: ${GREEN}高电平${NC}" || log INFO "$2 状态: ${RED}低电平${NC}"
            }
            exit $exit_code
        fi
        ;;
    
    install)
        # 安装 systemd 服务（首次运行时执行）
        SYSTEMD_SERVICE="[Unit]
Description=GPIO Control Service
After=sysinit.target

[Service]
Type=oneshot
ExecStart=/bin/bash $INSTALL_DIR/${SCRIPT_NAME}.sh enable all
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target"
        
        echo "$SYSTEMD_SERVICE" > "/etc/systemd/system/${SCRIPT_NAME}.service"
        systemctl daemon-reload
        systemctl enable --now ${SCRIPT_NAME}.service
        echo -e "${GREEN}服务安装完成！${NC}"
        systemctl status ${SCRIPT_NAME}.service --no-pager
        ;;
    
    *)
        echo -e "用法: $0 [操作] [参数]"
        echo -e "  ${GREEN}操作选项:${NC}"
        echo -e "    install       安装 systemd 服务（首次运行）"
        echo -e "    enable <名称> 启用单个 GPIO（如: enable GPIO4_B3）"
        echo -e "    enable all    启用所有配置的 GPIO"
        echo -e "    status <名称> 查看单个 GPIO 状态"
        echo -e "    status all    查看所有 GPIO 状态"
        echo -e "\n${YELLOW}当前配置的 GPIO:${NC}"
        for name in "${!GPIO_MAP[@]}"; do
            value="${GPIO_VALUE[$name]}"
            level_text="高电平"
            if [ "$value" = "0" ]; then
                level_text="低电平"
            fi
            echo "  - $name = ${GPIO_MAP[$name]}, 默认$level_text"
        done
        exit 1
        ;;
esac    